import axios from "axios"
import store from "../../store/index"
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 设置请求头
axios.defaults.timeout = 20000
// 不需要登陆接口
const http1 = axios.create({
  baseURL: '/api'
})
// 需要登录验证接口
const http2 = axios.create({
  baseURL: '/api'
})
// 加载组件
http1.interceptors.request.use(config => {
  store.commit('showLoading','正在加载...')
  return config
},error => {
  return Promise.reject(error)
})
// 登录验证拦截器
http2.interceptors.request.use(config => {
  if(store.state.isLogin){
    return config
  }else{
    store.dispatch('showHint',{title:'请先登录!',isFlag:false})
    return Promise.reject(new Error('not login'))
  }
},error => {
  console.log('请求拦截',error)
  return Promise.reject(error)
})

// 响应拦截器
http1.interceptors.response.use(ResSuccess,ResError)
http2.interceptors.response.use(ResSuccess,ResError)
function ResSuccess(response){
  console.log(response.data,response.config.url)
  store.commit('hideLoading')
  return response.data
}
function ResError(error){
  store.commit('hideLoading')
  store.dispatch('showHint',{title:'服务器繁忙!',isFlag:false})
  return Promise.reject(error)
}


// 封装表单数据
const formdata = function(obj){
  const data = new FormData()
  for(let i in obj)
    data.append(i,obj[i])
  return data
}

// 导出请求口
export const http = {
  post(url,data){
    return http1.post(url,formdata(data))
  },
  get(url){
    return http1.get(url)
  }
}

export const http_login = {
  async post(url,data){
    return http2.post(url,formdata(data)).catch(() => {})
  },
  get(url){
    return http2.get(url)
  }
}